/*
 * handleUpload function
 * Info:
 * This function is used to handle incoming upload requests.
 * e.g. a user wants to upload a file to the server.
 * the amount of bytes that should be written also have to be known
 * to check if the upload is complete or not.
 */

#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <sys/mman.h> //memory map files dingen
#include <semaphore.h>
#include <unistd.h>
#include <string.h>
#include "hfile.h"

//#define FILESIZE (sizeof(UPMAPFILE) * sizeof(int))
#define MSGERRFILE "ERROR"

int handleUpload(int clientNo, clientInfo client[])
{
    //create file on disk, if it exists, error (or overwrite, not sure which one yet)
    printf("handleUpload reached by clientNo: %d\n", client[clientNo].clientNo);
    if((client[clientNo].iFileFd = open(client[clientNo].filename, O_CREAT | O_RDWR | O_TRUNC, ACC_RIGHT))<0)
    {
        perror("can't create file:");
        return 0;
    }
    //end of file creation

    //notify CHP
    lseek(client[clientNo].iMapFd, 0, SEEK_SET);
    write(client[clientNo].iMapFd, "READY\0", 6);
    printf("cMap: %s\n", client[clientNo].cMapFile);
    sem_post(client[clientNo].semaphoreEmpty);

    //do-while loop for writing file to disk
    do
    {
        lseek(client[clientNo].iMapFd, 0, SEEK_SET);
        bzero(client[clientNo].tempBuff, CHUNKSIZE);
        sem_wait(client[clientNo].semaphoreFull);
        printf("cMap: %s\n", client[clientNo].cMapFile);
        printf("strlen cmap: %d\n", strlen(client[clientNo].cMapFile));
        printf("going to write\n");
        if((client[clientNo].amountRead = read(client[clientNo].iMapFd, client[clientNo].tempBuff, strlen(client[clientNo].cMapFile)))>0)
        {
            if((client[clientNo].amountWritten = write(client[clientNo].iFileFd, client[clientNo].tempBuff, client[clientNo].amountRead))!=client[clientNo].amountRead)
            {
                perror("write error");
            }
            printf("written: %s\n", client[clientNo].tempBuff);
        }
        sem_post(client[clientNo].semaphoreEmpty);
    }
    while(client[clientNo].amountRead == CHUNKSIZE); //we still have to determine what the message is for when we are done with a file
    //end of loop
close(client[clientNo].iFileFd);
printf("closed upfd\n");
return 0;
}
//end of handleUpload